package jjn.round1;

/**
 * 剑指 Offer 53 - I. 在排序数组中查找数字 I
 * 二分法解法，找到target之后，直接往左往右遍历，直到找到不相等的元素结束
 *
 * @author Jiang Jining
 * @since 2022-07-20 23:04
 */
public class Offer_53_SolutionWithBisection {
    
    public int search(int[] nums, int target) {
        int low = 0;
        int totalCount = 0;
        int high = nums.length - 1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (nums[mid] == target) {
                int curPosition = mid + 1;
                totalCount++;
                while (curPosition <= high) {
                    if (nums[curPosition] == target) {
                        totalCount++;
                    } else {
                        break;
                    }
                    curPosition++;
                }
                curPosition = mid - 1;
                while (curPosition >= low) {
                    if (nums[curPosition] == target) {
                        totalCount++;
                    } else {
                        break;
                    }
                    curPosition--;
                }
                return totalCount;
            } else if (nums[mid] < target) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
        return totalCount;
    }
}
